﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using QYWXUpdate.DataModel;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

public class QywxService
{
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly string _corpId;
    private readonly string _secret;
    private readonly string _agentId;
    private string _accessToken;
    private DateTime _tokenExpireTime;

    public QywxService(IHttpClientFactory httpClientFactory, IConfiguration configuration)
    {
        _httpClientFactory = httpClientFactory;
        _corpId = configuration["QywxSettings:CorpId"];
        _secret = configuration["QywxSettings:Secret"];
        _agentId = configuration["QywxSettings:AgentId"];
    }

    public async Task<string> GetAccessTokenAsync()
    {
        //if (!string.IsNullOrEmpty(_accessToken) && DateTime.Now < _tokenExpireTime)
        //{
        //    return _accessToken;
        //}

        //var client = _httpClientFactory.CreateClient();
        //var response = await client.GetAsync(
        //    $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={_corpId}&corpsecret={_secret}");

        //response.EnsureSuccessStatusCode();
        //var result = JsonConvert.DeserializeObject<QywxTokenResponse>(
        //    await response.Content.ReadAsStringAsync());

        //if (result?.errcode != 0)
        //{

        //    throw new Exception($"获取AccessToken失败: {result?.errmsg}");
        //}

        //_accessToken = result.access_token;
        //_tokenExpireTime = DateTime.Now.AddSeconds(result.expires_in - 300);
        //return _accessToken;

        //var Secret = Cryptography.EncryptByAES(_secret, "xshAesKey0000000", "1234567890abcdef");
        var Secret = AesCbcHelper.Encrypt(_secret, System.Text.Encoding.Default.GetBytes("xshAesKey1234567"), System.Text.Encoding.Default.GetBytes("1234567890abcdef"));

        var content = new
        {
            mode = "qywxupdate",
            corpId = _corpId,
            secret = Secret
        };

        var client = _httpClientFactory.CreateClient();
        client.DefaultRequestHeaders.Add("ContentType", "application/json");

        var postContent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://ziyan.xshhotels.cn:8687/qwApi/getToken", postContent);


        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();
            
            using (responseStream)
            {
                var res =  await StreamToStringAsync(responseStream);
                var result = JsonConvert.DeserializeObject<TokenResponse>(res);
                if (result != null &&result.code == 200)
                {
                    return result.body;
                }
            }
            
        }
            return "";
    }

    /// <summary>
    /// 数据流转String
    /// </summary>
    /// <param name="stream"></param>
    /// <returns></returns>
    public async Task<string> StreamToStringAsync(Stream stream)
    {
        if (stream.CanSeek)
        {
            stream.Seek(0, SeekOrigin.Begin);
        }

        using (StreamReader reader = new StreamReader(stream))
        {
            return await reader.ReadToEndAsync();
        }
    }

    public async Task SetWorkbenchTemplateAsync()
    {
        var token = await GetAccessTokenAsync();
        //var client = _httpClientFactory.CreateClient();

        //var templateData = new
        //{
        //    agentid = _agentId,
        //    type = "keydata",
        //    keydata = new
        //    {
        //        items = new[]
        //        {
        //            new { key = "待审批", data = "0", jump_url = "https://yourdomain.com/approval" },
        //            new { key = "待处理", data = "0", jump_url = "https://yourdomain.com/todo" }
        //        }
        //    }
        //};

        //var content = new StringContent(
        //    JsonConvert.SerializeObject(templateData),
        //    System.Text.Encoding.UTF8,
        //    "application/json");

        //var response = await client.PostAsync(
        //    $"https://qyapi.weixin.qq.com/cgi-bin/agent/set_workbench_template?access_token={token}",
        //    content);

        //if (response.IsSuccessStatusCode)
        //{
        //    var responseStream = await response.Content.ReadAsStreamAsync();

        //    using (responseStream)
        //    {
        //        var res = await StreamToStringAsync(responseStream);
        //    }

        //}

        //response.EnsureSuccessStatusCode();
    }

    public async Task<string> UpdateUserWorkbenchDataAsync(int pendingApproval, int pendingTasks,int type)
    {
        var token = await GetAccessTokenAsync();
        var client = _httpClientFactory.CreateClient();

        var dyType = new object();
        var contentDate = new object();

        switch (type)
        {
            case 1:
                dyType = new KeyType()
                {
                    key = "待处理",
                    data = "2",
                    jump_url = "http://www.qq.com",
                    pagepath = "pages/index"
                };
                contentDate = new
                {
                    agentid = _agentId,
                    type = "keydata",
                    keydata = dyType
                };
                break;
            case 2:
                dyType = new PictureType()
                {
                    url = "",
                    jump_url = "http://www.qq.com",
                    pagepath = "pages/index"
                };
                contentDate = new
                {
                    agentid = _agentId,
                    type = "keydata",
                    image = dyType
                };
                break;
            case 3:
                dyType = new ListType()
                {
                    title = "sadas",
                    jump_url = "http://www.qq.com",
                    pagepath = "pages/index"
                };
                contentDate = new
                {
                    agentid = _agentId,
                    type = "keydata",
                    list = dyType
                };
                break;
        }

        

        var temp = JsonConvert.SerializeObject(contentDate);

        var content = new StringContent(
            JsonConvert.SerializeObject(contentDate),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = await client.PostAsync(
            $"https://qyapi.weixin.qq.com/cgi-bin/agent/set_workbench_data?access_token={token}",
            content);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await StreamToStringAsync(responseStream);
                return res;
            }

        }

        response.EnsureSuccessStatusCode();
        return "推送错误";
    }
}

public class QywxTokenResponse
{
    public int errcode { get; set; }
    public string errmsg { get; set; }
    public string access_token { get; set; }
    public int expires_in { get; set; }
}

